package com.springboot.fastcode.config;


import java.io.File;
import java.io.IOException;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

@Component
public class FreeMarkerInit {

    @Autowired
    private ResourceLoader resourceLoader;

    private static final FreeMarkerInit single = new FreeMarkerInit();

    private FreeMarkerInit() {}

    //静态工厂方法
    public static FreeMarkerInit getInstance() {
        return single;
    }

    public Template getDefinedTemplate(String templatePath, String templateName) throws IOException {
        //配置类
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        Resource resource = resourceLoader.getResource(templatePath);
        // Resource resource = resourceLoader.getResource("classpath:templates/");
        cfg.setDirectoryForTemplateLoading(resource.getFile());
       // cfg.setDirectoryForTemplateLoading(new File("D:/springboot/fast-code/src/main/resources/templates/"));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        return cfg.getTemplate(templateName);
    }
}
